# -*- coding: utf-8 -*-

import GUI.gui
import wx
import helpers.tabcontainer

class BooksView():
    # @type frame GUI.gui.frame_main
    frame = None
    controller = None
    newBookTabTitle = u"Nová publikace"
    existingBookTabTitle = u"Publikace - "
    booksPanelVisible = True
    notesPanelVisible = True
    bookIdMap = {}
    noteBookIdMap = {}
    tagMap = {}
    tabContainer = None

    def __init__(self, controller, frame):
        self.tabContainer = helpers.tabcontainer.TabContainer.getInstance("main")
        self.frame = frame
        self.controller = controller

        self.frame.list_books.InsertColumn(0, u"Název")
        self.frame.list_noteBooks.InsertColumn(0, u"Název")

        self.frame.Bind(wx.EVT_BUTTON, controller.newAction, frame.button_newBook)
        self.frame.Bind(wx.EVT_BUTTON, controller.saveAction, frame.button_bookSave)

        self.frame.list_books.Bind(wx.EVT_CONTEXT_MENU, self.showContextMenu)
        self.frame.Bind(wx.EVT_MENU, controller.newAction, frame.menu_newBook)
        self.frame.Bind(wx.EVT_MENU, controller.deleteAction, frame.menu_deleteBooks)

        self.frame.list_books.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.onBookActivate)
        self.frame.list_tags.Bind(wx.EVT_LISTBOX, self.onTagsSelected)
        self.frame.list_noteTags.Bind(wx.EVT_LISTBOX, self.onNoteTagsSelected)

        self.frame.Bind(wx.EVT_MENU, controller.newAction, frame.menu_fileNewBook)

    def showBooksPanel(self, bookTitle = None):
        tabName = self.newBookTabTitle
        if bookTitle is not None:
            tabName = self.existingBookTabTitle + "\"" + bookTitle + "\""

        if self.booksPanelVisible == True:
            self.frame.notebook_main.SetPageText(self.tabContainer.getPanelByName("book"), tabName)
            return

        self.frame.notebook_main.InsertPage(self.tabContainer.addPanel("book"), self.frame.panel_book, tabName, True)
        self.frame.panel_book.Show(True)
        self.booksPanelVisible = True

    def hideBooksPanel(self):
        if self.booksPanelVisible == False:
            return
        self.frame.panel_book.Show(False)
        self.frame.notebook_main.RemovePage(self.tabContainer.getPanelByName("book"))
        self.tabContainer.remPanel("book")
        self.booksPanelVisible = False

    def resetBooksPanel(self):
        self.frame.text_bookName.Clear()
        self.frame.text_bookAuthor.Clear()
        self.frame.text_bookGenre.Clear()
        self.frame.text_bookISBN.Clear()
        self.frame.text_bookDesc.Clear()
        self.frame.text_bookTags.Clear()
        self.frame.notebook_book.ChangeSelection(0)

    def focusBooksPanel(self):
        if self.booksPanelVisible == False:
            return
        self.frame.notebook_main.ChangeSelection(self.tabContainer.getPanelByName("book"))

    def getBookBasicData(self):
        data = {}
        data["name"] = self.frame.text_bookName.GetValue()
        data["author"] = self.frame.text_bookAuthor.GetValue()
        data["genre"] = self.frame.text_bookGenre.GetValue()
        data["isbn"] = self.frame.text_bookISBN.GetValue()
        data["descr"] = self.frame.text_bookDesc.GetValue()
        data["tags"] = self.frame.text_bookTags.GetValue()

        return data

    def showError(self, error):
        dialog = wx.MessageDialog(self.frame, error, u"Chyba", wx.OK | wx.ICON_EXCLAMATION)
        dialog.ShowModal()

    def updateBookLists(self, books):
        self.frame.list_books.DeleteAllItems()

        self.bookIdMap.clear()

        for i, book in enumerate(books.itervalues()):
            self.bookIdMap[i] = book["id"]
            index = self.frame.list_books.InsertStringItem(0, book["name"])
            self.frame.list_books.SetItemData(index,i)

    def updateNoteBookLists(self, books):
        self.frame.list_noteBooks.DeleteAllItems()

        self.noteBookIdMap.clear()

        for i, book in enumerate(books.itervalues()):
            self.noteBookIdMap[i] = book["id"]
            index = self.frame.list_noteBooks.InsertStringItem(0, book["name"])
            self.frame.list_noteBooks.SetItemData(index, i)


    def setStatus(self, status):
        self.frame.SetStatusText(status)

    def showContextMenu(self, event):
        self.frame.list_books.PopupMenu(self.frame.menu_booksList)

    def showDeleteConfirmDialog(self, books):
        text =  u"Přejete si opravdu odstranit tyto publikace a všechny obsažené poznámky?\n"
        for book in books.itervalues():
            text += "\n" + book["name"][:50] + ("..." if len(book["name"]) > 50 else "")
        dialog = wx.MessageDialog(self.frame, text, u"Opravdu smazat?", wx.YES_NO | wx.ICON_EXCLAMATION)
        return dialog.ShowModal() == wx.ID_YES

    def getSelectedBookIds(self):
        item = -1
        books = []
        while True:
            item = self.frame.list_books.GetNextItem(item, state = wx.LIST_STATE_SELECTED)
            if item == -1:
                break
            books.append(self.bookIdMap[self.frame.list_books.GetItem(item).GetData()])

        return books

    def getSelectedNoteBookId(self):
        item = self.frame.list_noteBooks.GetNextItem(-1, state = wx.LIST_STATE_SELECTED)
        if item == -1:
            return None

        return self.noteBookIdMap[self.frame.list_noteBooks.GetItem(item).GetData()]

    def onBookActivate(self, event):
        self.controller.editAction(self.bookIdMap[event.GetData()])

    def setActiveBook(self, book):
        if "name" in book : self.frame.text_bookName.SetValue(book["name"])
        if "author" in book : self.frame.text_bookAuthor.SetValue(book["author"])
        if "genre" in book : self.frame.text_bookGenre.SetValue(book["genre"])
        if "isbn" in book : self.frame.text_bookISBN.SetValue(book["isbn"])
        if "descr" in book : self.frame.text_bookDesc.SetValue(book["descr"])
        if "tags" in book : self.frame.text_bookTags.SetValue(book["tags"])

    def updateTagsLists(self, tags):
        self.frame.list_tags.Clear()
        self.frame.list_noteTags.Clear()
        self.frame.list_tags.InsertItems(tags.keys(), 0)
        self.frame.list_noteTags.InsertItems(tags.keys(), 0)

    def onTagsSelected(self, event):
        tagIndices = self.frame.list_tags.GetSelections()
        items = self.frame.list_tags.GetStrings()

        tags = []
        for index in tagIndices:
            tags.append(items[index])
        self.controller.refreshBookListsAction(tags = tags)

    def onNoteTagsSelected(self, event):
        tagIndices = self.frame.list_noteTags.GetSelections()
        items = self.frame.list_noteTags.GetStrings()

        tags = []
        for index in tagIndices:
            tags.append(items[index])
        self.controller.refreshNoteBookListsAction(tags = tags)

    def showNotesPanel(self):
        if self.notesPanelVisible == True:
            return

        self.frame.notebook_book.InsertPage(1, self.frame.panel_bookNotes, u"Poznámky", True)
        self.frame.panel_bookNotes.Show(True)
        self.notesPanelVisible = True
        self.frame.notebook_book.ChangeSelection(0)


    def hideNotesPanel(self):
        if self.notesPanelVisible == False:
            return
        self.frame.panel_bookNotes.Show(False)
        self.frame.notebook_book.RemovePage(1)
        self.notesPanelVisible = False

    def enableGeneralPanel(self, enable):
        self.frame.panel_bookGeneralInfo.Enable(enable)
        self.frame.button_bookSave.Enable(enable)